/**
 * 工时数据图表组件
 */

'use client';

import React, { useMemo } from 'react';
import { Card, Row, Col, Empty, Typography } from 'antd';
import { PieChart, Pie, Cell, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, LineChart, Line } from 'recharts';
import dayjs from 'dayjs';
import type { Workload } from '../types/workload';
import type { 
  ProjectWorkloadSummary, 
  WorkloadChartData, 
  TimeSeriesData, 
  ProjectComparisonData 
} from '../types/workloadStats';

const { Text, Title } = Typography;

interface WorkloadChartsProps {
  projectSummaries: ProjectWorkloadSummary[];
  chartData: WorkloadChartData[];
  timeSeriesData: TimeSeriesData[];
  comparisonData: ProjectComparisonData[];
  loading?: boolean;
  onProjectClick?: (project: ProjectWorkloadSummary) => void;
}

// 图表颜色配置
const COLORS = [
  '#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1',
  '#13c2c2', '#eb2f96', '#fa8c16', '#a0d911', '#2f54eb'
];

export default function WorkloadCharts({
  projectSummaries,
  chartData,
  timeSeriesData,
  comparisonData,
  loading = false,
  onProjectClick,
}: WorkloadChartsProps) {
  // 项目工时饼图数据
  const projectPieData = useMemo(() => {
    if (!chartData || chartData.length === 0) return [];
    
    const totalHours = chartData.reduce((sum, item) => sum + item.hours, 0);
    
    return chartData
      .slice(0, 10) // 只显示前10个项目
      .map((item, index) => ({
        name: item.name.length > 15 
          ? `${item.name.substring(0, 15)}...` 
          : item.name,
        value: item.hours,
        fullName: item.name,
        percentage: ((item.hours / totalHours) * 100).toFixed(1),
        color: COLORS[index % COLORS.length],
      }));
  }, [chartData]);

  // 成员工时柱状图数据
  const memberBarData = useMemo(() => {
    if (!projectSummaries || projectSummaries.length === 0) return [];
    
    // 汇总所有项目的成员统计
    const memberMap = new Map<string, { name: string; hours: number }>();
    
    projectSummaries.forEach(project => {
      project.memberStats?.forEach(member => {
        const existing = memberMap.get(member.memberId);
        if (existing) {
          existing.hours += member.totalHours;
        } else {
          memberMap.set(member.memberId, {
            name: member.memberName,
            hours: member.totalHours
          });
        }
      });
    });
    
    return Array.from(memberMap.values())
      .sort((a, b) => b.hours - a.hours)
      .slice(0, 10) // 只显示前10个成员
      .map(member => ({
        name: member.name.length > 8 
          ? `${member.name.substring(0, 8)}...` 
          : member.name,
        fullName: member.name,
        duration: member.hours,
        percentage: '0', // 暂时设为0，后续可以计算
      }));
  }, [projectSummaries]);

  // 工时类型分布数据
  const typeDistributionData = useMemo(() => {
    if (!projectSummaries || projectSummaries.length === 0) return [];
    
    // 汇总所有项目的工时类型统计
    const typeMap = new Map<string, number>();
    let totalHours = 0;
    
    projectSummaries.forEach(project => {
      project.workloadTypes?.forEach(type => {
        if (type) {
          typeMap.set(type, (typeMap.get(type) || 0) + project.totalHours / (project.workloadTypes?.length || 1));
          totalHours += project.totalHours / (project.workloadTypes?.length || 1);
        }
      });
    });
    
    return Array.from(typeMap.entries()).map(([typeName, hours], index) => ({
      name: typeName,
      value: hours,
      percentage: totalHours > 0 ? ((hours / totalHours) * 100).toFixed(1) : '0',
      color: COLORS[index % COLORS.length],
    }));
  }, [projectSummaries]);

  // 时间趋势数据（按天统计）
  const timeTrendData = useMemo(() => {
    if (!timeSeriesData || timeSeriesData.length === 0) return [];

    return timeSeriesData.map(item => ({
      date: item.date,
      duration: Number(item.hours.toFixed(1)),
      displayDate: dayjs(item.date).format('MM-DD'),
    }));
  }, [timeSeriesData]);

  // 自定义饼图标签
  const renderPieLabel = (entry: any) => {
    return `${entry.percentage}%`;
  };

  // 自定义饼图提示
  const renderPieTooltip = (props: any) => {
    const { active, payload } = props;
    if (active && payload && payload.length) {
      const data = payload[0].payload;
      return (
        <div className="bg-white p-3 border border-gray-200 rounded shadow-lg">
          <p className="font-medium">{data.fullName}</p>
          <p className="text-blue-600">工时: {data.value.toFixed(1)} 小时</p>
          <p className="text-gray-600">占比: {data.percentage}%</p>
        </div>
      );
    }
    return null;
  };

  // 自定义柱状图提示
  const renderBarTooltip = (props: any) => {
    const { active, payload } = props;
    if (active && payload && payload.length) {
      const data = payload[0].payload;
      return (
        <div className="bg-white p-3 border border-gray-200 rounded shadow-lg">
          <p className="font-medium">{data.fullName}</p>
          <p className="text-blue-600">工时: {data.duration.toFixed(1)} 小时</p>
          <p className="text-gray-600">占比: {data.percentage}%</p>
        </div>
      );
    }
    return null;
  };

  if (loading) {
    return (
      <Card title="数据分析图表" loading={true}>
        <div style={{ height: 400 }} />
      </Card>
    );
  }

  if (!projectSummaries || projectSummaries.length === 0) {
    return (
      <Card title="数据分析图表">
        <Empty description="暂无数据" />
      </Card>
    );
  }

  return (
    <div className="space-y-6">
      {/* 第一行：项目工时分布和用户工时排名 */}
      <Row gutter={[16, 16]}>
        <Col xs={24} lg={12}>
          <Card title="项目工时分布" size="small">
            <ResponsiveContainer width="100%" height={300}>
              <PieChart>
                <Pie
                  data={projectPieData}
                  cx="50%"
                  cy="50%"
                  labelLine={false}
                  label={renderPieLabel}
                  outerRadius={80}
                  fill="#8884d8"
                  dataKey="value"
                >
                  {projectPieData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} />
                  ))}
                </Pie>
                <Tooltip content={renderPieTooltip} />
                <Legend />
              </PieChart>
            </ResponsiveContainer>
          </Card>
        </Col>
        
        <Col xs={24} lg={12}>
          <Card title="成员工时排名" size="small">
            {memberBarData.length > 0 ? (
              <ResponsiveContainer width="100%" height={300}>
                <BarChart data={memberBarData} margin={{ top: 20, right: 30, left: 20, bottom: 5 }}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis 
                    dataKey="name" 
                    angle={-45}
                    textAnchor="end"
                    height={80}
                  />
                  <YAxis />
                  <Tooltip content={renderBarTooltip} />
                  <Bar dataKey="duration" fill="#1890ff" />
                </BarChart>
              </ResponsiveContainer>
            ) : (
              <Empty description="暂无成员工时数据" />
            )}
          </Card>
        </Col>
      </Row>

      {/* 第二行：工时类型分布和时间趋势 */}
      <Row gutter={[16, 16]}>
        <Col xs={24} lg={12}>
          <Card title="工时类型分布" size="small">
            {typeDistributionData.length > 0 ? (
              <ResponsiveContainer width="100%" height={300}>
                <PieChart>
                  <Pie
                    data={typeDistributionData}
                    cx="50%"
                    cy="50%"
                    labelLine={false}
                    label={renderPieLabel}
                    outerRadius={80}
                    fill="#8884d8"
                    dataKey="value"
                  >
                    {typeDistributionData.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={entry.color} />
                    ))}
                  </Pie>
                  <Tooltip content={renderPieTooltip} />
                  <Legend />
                </PieChart>
              </ResponsiveContainer>
            ) : (
              <Empty description="暂无工时类型数据" />
            )}
          </Card>
        </Col>
        
        <Col xs={24} lg={12}>
          <Card title="工时趋势分析" size="small">
            {timeTrendData.length > 0 ? (
              <ResponsiveContainer width="100%" height={300}>
                <LineChart data={timeTrendData} margin={{ top: 20, right: 30, left: 20, bottom: 5 }}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis 
                    dataKey="displayDate"
                    angle={-45}
                    textAnchor="end"
                    height={80}
                  />
                  <YAxis />
                  <Tooltip 
                    formatter={(value: number) => [`${value} 小时`, '工时']}
                    labelFormatter={(label) => `日期: ${label}`}
                  />
                  <Line 
                    type="monotone" 
                    dataKey="duration" 
                    stroke="#1890ff" 
                    strokeWidth={2}
                    dot={{ fill: '#1890ff', strokeWidth: 2, r: 4 }}
                  />
                </LineChart>
              </ResponsiveContainer>
            ) : (
              <Empty description="请选择日期范围查看趋势" />
            )}
          </Card>
        </Col>
      </Row>
    </div>
  );
}